import { observable, action } from 'mobx';
import service from "../libs/request";
import { message } from "antd";

class FormJsStore{
    @observable actions = [];

    @action setActions(actions){
        this.actions = actions;
    }

    @observable form;
    
    @action setFrom(from){
        this.form = from;
    }

    @observable options = [];

    @action setOptions(key , option){
        this.options[key] = option;
    }

    @action cleanOptions(){
        this.options = [];
        console.log("FormJsStore cleanOptions");
    }

    @action watchAction(key,value){
        console.log("watchAction",this.actions,key);
        if(this.actions && (this.options).length > 0){
            this.actions.map((item,index)=>{
                const i =  item.watchFields.find(item =>{
                    console.log("findIndex item",item,key,item === key)
                    return item === key;
                });
                console.log("i:",i);
                if(i === key){
                    this.runAction(item, key,value)
                }
            })
        }

    }

    runAction(item, key,value){
        console.log("runAction",item,key);
        this.form.validateFields((err, formData) => {
            let changeForm = {[key] :value};
            formData = {...formData,...changeForm};
            if(item.action == 'getValid'){
                service.request({
                    url:item.uri,
                    method:"post",
                    data:formData,
                }).then(response => {
                    if (response.data.code === 200){
                        Object.keys(response.data.data).forEach(id => {
                            const re_item = response.data.data[id];
                            console.log("re_item",re_item);
                            if(re_item.type == 'selectOption'){
                                this.setOptions(key,re_item.options);
                            }
                        });
                    }else {
                        message.error(response.data.msg);
                    }
                }).catch(err=>{

                })
            }

        });
    }
}

export default new FormJsStore()